<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\handler\CurlHandler;
use Couchbase\ValueRecorder;
use app\api\model\wanlshop\PayOutTrade;
class Fuhave extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $test = false;
    protected static $url;
    protected static $refund;
    protected static $mchnt_cd;
    protected $ver = "1.0.0"; //版本号
    protected static $fuHavePublicKey; //富有公钥
    protected static $mchPrivateKey; //商户私钥
    protected $appid = 'wx4b0608b9f9bba7ac';
    public function __construct(){
        if ($this->test){
            //正式环境
            self::$url = "https://aggpcpay.fuioupay.com/aggpos/";
            self::$refund = "https://refund-transfer.fuioupay.com/refund_transfer/";
            self::$mchnt_cd = "";
            self::$fuHavePublicKey = "";
            self::$mchPrivateKey = "";
        }else{
            //测试环境
            self::$url = "https://aggpc-test.fuioupay.com/aggpos/";
            self::$refund = "https://refund-transfer-test.fuioupay.com/refund_transfer/";
            self::$mchnt_cd = "0001000F0040992";
            self::$fuHavePublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCKPD4f/3xMjPuHcQSGxPIYZNgF2i0sJhzmKpN3dmzhbKH/1nG+aXUJDhswyitzrI+U0ic/GL/IWB1wQ3noWuLFr8jDSGafenTFiY9c0H9ZAEfqW/oywx95G5JWu5y/ffp4yCmlt8k5kHO/4kE1qnJcGaQlb6/+7t3MPSV5ybmBZwIDAQAB";
            self::$mchPrivateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJMr8NnRV7ve7Y5FEBium/TsU0fK5NvzvFpsYxPAQhBXY+EN0Bi2JEg790C1njk9Q3U36u2JBDHAiDIomlgh6wWkJsFn7dghV/fCWSX1VVJ+dRINZy1432fRaJ8GqspvMneBpeLjBe94IwlWKpN+AOR+BNX8QL/uHmfCPlVQXos9AgMBAAECgYAzqbMs434m50UBMmFKKNF6kxNRGnpodBFktLO7FTybu/HF6TFp21a1PMe5IYhfk5AAsBZ6OCUOygWFhhdYZN+5W+dweF3kp1rLE4y5CjwqNlk/g22TAndf9znh/ltHFLvITToqu/eh/34tE1gyNxRbsi1olw/1wv8ZRjM3vtM9QQJBANvNwFq+CJHUyFzkXQB7+ycQFnY8wDq8Uw2Hv9ZMjgIntH7FSlJtdu5mAYPPo6f74slO5tFUMNP7EVppqsjYaNkCQQCraD6iKHo+OIlvvYIKiMXatJGD7N1GNhq5CrhUNPWLHwv/Ih2D3JJdF8IUZOPIJfUxTfM2fZYI+EVdsv6s4RcFAkAGjNYbnighOGcUJZYD6q3sVxVkRqEv3ubWs2HrH/Lna4l8caKqXCq8JfwLkod8/QugFiLYwBqIZqX4vMdjHtfZAkBsAl9dbWZCaPvpxp/4JWGPxDLhz9NLV/KU4bVvkoObq++yUHwKyGYOdVcd5MlIKOsNq5Hzp0Vw14lWVuF2bMxFAkBuNrZksvUULNIaWDKd4rQ6GVzUxXuIZW0ZE6atHYDiXPB4jVAjKRtLxZAV1qH9cr1zNJlcg+RbGYUdF9t4A9n5";
        }
    }
    //使用【富友公钥】加密报文
    public function encryptedMessage($plaintext){
        // 将数据转换为 JSON 格式
        $plaintext = json_encode($plaintext);
        // 载入富友的公钥
        $pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" . chunk_split(self::$fuHavePublicKey, 64, "\n") . "-----END PUBLIC KEY-----";
        $publicKey = openssl_pkey_get_public($pemPublicKey);
        $encrypted = '';
        $key_len = openssl_pkey_get_details($publicKey)['bits'];
        $part_len = $key_len / 8 - 11;
        $parts = str_split($plaintext, $part_len);
        foreach ($parts as $part) {
            $encrypted_temp = '';
            openssl_public_encrypt($part, $encrypted_temp, $publicKey);
            $encrypted .= $encrypted_temp;
        }

        return base64_encode($encrypted);
    }
    //使用【商户私钥】解密报文
    public function decryptWithMerchantPrivateKey($encryptedData){
        $pemPrivateKey = "-----BEGIN PRIVATE KEY-----\n" . chunk_split(self::$mchPrivateKey, 64, "\n") . "-----END PRIVATE KEY-----";
        $privateKey = openssl_pkey_get_private($pemPrivateKey);
        $decodedData = base64_decode($encryptedData);
        $crypto = '';
        foreach (str_split($decodedData, 128) as $chunk) {
            openssl_private_decrypt($chunk, $decryptData, $privateKey);
            $crypto .= $decryptData;
        }
        return $crypto;
    }
    public function fuHave($url,$data){
        $handler = new CurlHandler();
        $res = $handler->curlRequest([
            'url'=>$url,
            'method'=>'POST',
            'headers'=>[
                "Content-Type:application/json;charset=UTF-8",
                "User-Agent:API Explorer"
            ],
        ],$data);

        if($res['httpCode'] == 200){
            $body = json_decode($res['body']);
            $message = $body->message;
            $decryptedData = $this->decryptWithMerchantPrivateKey($message);
            $body->message = json_decode($decryptedData);
            return $body;
        }else{
            return json_decode($res['body']);
        }

    }
    //获取openid
    public function openId(){
        $url = self::$url.'getOpenid.fuiou';
        $redirect_uri = "https://xinweidu.enjoysix.com/api/fuhave/getOpenId";
        $data = [
            'mchnt_cd'=>self::$mchnt_cd,
            'redirect_uri'=>$redirect_uri,
            'ver'=>$this->ver
        ];
        $encryptedData = $this->encryptedMessage($data);
        $params['mchnt_cd'] = self::$mchnt_cd;
        $params['message'] = $encryptedData;
        $res = $this->fuHave($url,$params);
        return json([
            'msg'=> '请求成功',
            'code'=>200,
            'data'=>$res
        ]);
//        $this->success('请求成功',$res);
    }

    public function getOpenId(){

    }
    //订单支付接口
    public function pay($param){
        extract($param);
        $url = self::$url.'order.fuiou';
        $payOutTrade = PayOutTrade::where('out_trade_no',$mchOrderNo)->find();
        $good = model('app\api\model\wanlshop\OrderGoods')::where('order_id',$payOutTrade->order_id)->find();
        $subject = $good->title??'商品标题';
        $body = $good->title??'商品描述';
        $reqTime = time() ;
        $formattedDate = date('Ymd',$reqTime);
        $data = [
            'mchnt_cd'=>self::$mchnt_cd,
            'ver'=>$this->ver,
            'order_date'=>$formattedDate,   //订单日期
            'order_id'=> $mchOrderNo,  //订单号
            'order_amt'=>(int)$amount*100, //订单金额
            'order_pay_type'=>'LETPAY', //支付方式
            'back_notify_url'=>'https://xinweidu.enjoysix.com/api/wanlshop/callback/cailaiju_notify', //回调地址
            'goods_name'=>mb_substr($subject, 0, 15, 'UTF-8'), //商品名称
            'goods_detail'=> $body,//商品描述
            'appid'=>$appid, //appid
            'openid'=>$openid,//openid
        ];
        $encryptedData = $this->encryptedMessage($data);
        $params['mchnt_cd'] = self::$mchnt_cd;
        $params['message'] = $encryptedData;
        $res = $this->fuHave($url,$params);
        return $res;
    }
}